package part1basiclock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

// 验证可重入锁 -> ReentrantLock
public class TestLock07 {

    public static void main(String[] args) throws Exception {
        Phone02 phone = new Phone02();
        // T1 线程在外层获取锁时，也会自动获取里面的锁
        new Thread(phone, "T1").start();
        new Thread(phone, "T2").start();
    }

}

class Phone02 implements Runnable {

    Lock lock = new ReentrantLock();

    @Override
    public void run() {
        get();
    }

    public void get() {
        lock.lock();
        // lock.lock(); 锁必须匹配，如果两个锁，只有一个解锁就会失败
        try {
            System.out.println(Thread.currentThread().getName() + " get()");
            set();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void set() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + " set()");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}
